import fileinput
import logging
import sys
from logging.handlers import TimedRotatingFileHandler


def init_log(name='abaqus', config: dict = None):
    if config is None:
        config = {}

    _logger = logging.getLogger(name)
    if len(_logger.handlers) > 0:
        return _logger

    log_file = config.get('filePath')
    level = config.get('level', 'INFO')
    backup_count = config.get('maxBackups', '7')

    _logger.setLevel(level)
    format_str = logging.Formatter('%(asctime)-15s %(name)s %(process)d %(levelname)-8s %(message)s')

    stream_handler = logging.StreamHandler(stream=sys.stdout)
    stream_handler.setFormatter(format_str)
    _logger.addHandler(stream_handler)

    if log_file:
        rotate_handler = TimedRotatingFileHandler(log_file, when='D', backupCount=int(backup_count))
        rotate_handler.setFormatter(format_str)
        _logger.addHandler(rotate_handler)

    return _logger


def inp_file_replace_line(fname, replace_info={}):
    replace_val = None
    skip_num = 0
    for line in fileinput.input(fname, inplace=1):
        if replace_val is not None:
            skip_num = len(replace_val) - 1
            for i in range(len(replace_val)):
                for j in range(len(replace_val[i])):
                    sys.stdout.write(str(replace_val[i][j]))
                    if j < len(replace_val[i])-1:
                        sys.stdout.write(',')
                sys.stdout.write('\n')
            replace_val = None
            continue
        replace_val = replace_info.get(line, None)
        if skip_num > 0:
            skip_num = skip_num - 1
        else:
            sys.stdout.write(line)


if __name__ == '__main__':
    fname = "/Users/luotao/Desktop/test.inp"
    re = {"aa\n": [[1,2], [1,2]], "cc\n": [['3', '4']]}
    inp_file_replace_line(fname, re)
